package com.pyue.eam.app.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pyue.eam.admin.api.except.ApiAsserts;
import com.pyue.eam.app.api.entity.AppTabbarEntity;
import com.pyue.eam.app.mapper.AppTabbarMapper;
import com.pyue.eam.app.service.AppTabbarService;
import com.pyue.eam.common.core.constant.CacheConstants;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 导航栏
 *
 * @author eam
 * @date 2023-06-08 11:18:46
 */
@Service
@AllArgsConstructor
public class AppTabbarServiceImpl extends ServiceImpl<AppTabbarMapper, AppTabbarEntity> implements AppTabbarService {
    private final StringRedisTemplate redisTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateTabbar(List<AppTabbarEntity> tabbarEntityList) {
        Integer roleTypeId = CollUtil.getFirst(tabbarEntityList).getTypeId();
        ApiAsserts.isTrue(roleTypeId != null, "类型不能为空");
        // 删除缓存
        redisTemplate.delete(CacheConstants.GLOBALLY + "app:config" + roleTypeId);

        // 删除不在新增范围的导航菜单
        List<Long> idList = lambdaQuery().eq(AppTabbarEntity::getTypeId, roleTypeId).list()
                .stream().map(AppTabbarEntity::getId)
                .collect(Collectors.toList());
        List<Long> newIdList = tabbarEntityList.stream().map(AppTabbarEntity::getId).collect(Collectors.toList());
        removeBatchByIds(CollUtil.subtractToList(idList, newIdList));
        return saveOrUpdateBatch(tabbarEntityList);
    }
}
